App = {
  web3Provider: null,
  contracts: {},

  shopArray: [],  //购买的东西数组
  payedmoney: 0,  //花费的钱
  shopid : 0,

  jifenid: 0,
  jifenstr: "",
  jifenall: 0,

  init: async function () {
    // Load shopmal.
    let paramstr = decodeURI(location.search)
    let index = paramstr.indexOf("?")
    let params = paramstr.substring(index+1)
    App.jifenid = parseInt(params.split("&")[0].split("=")[1])
    App.jifenstr = params.split("&")[1].split("=")[1]
    App.jifenall = parseInt(params.split("&")[2].split("=")[1])
    let arr = App.jifenstr.split(",")
    console.log(arr)
    $('.myscore').text(App.jifenall)
    var petsRow = $('#shopmal');
    var petTemplate = $('#shopTemplate');
    var cardwidth = $(window).width() - 99;
    for (i = 0; i < arr.length; i++) {
      let score = parseInt(arr[i].split("-")[1])
      let rules = `线上消费${score*10}元`
      petTemplate.find('.card').css("width",cardwidth);
      petTemplate.find('.score').text(score);      
      petTemplate.find('.rules').text(rules);
      petTemplate.find('.choose').attr('data-scoreid', parseInt(arr[i].split("-")[0]));
      petTemplate.find('.choose').attr('data-score', score);
      petsRow.append(petTemplate.html());
    } 
    return await App.initWeb3();
  },

  initWeb3: async function () {
    // Modern dapp browsers...
    if (window.ethereum) {
      console.log('1')
      App.web3Provider = window.ethereum;
      try {
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      console.log('2')
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
      console.log('3')
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {
    // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
    $.getJSON('Adoption.json', function (data) {
      // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
      App.contracts.Adoption = TruffleContract(data);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      App.contracts.Adoption.deployed().then(function(instance){
        App.adoptionInstance = instance;
        //return App.mymoney();
      })
      // Use our contract to retrieve and mark the adopted pets
      //return App.markAdopted();
    });
    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.back', App.jump);
    $(document).on('click', '.choose', App.select);
    $(document).on('click', '.chooseall', App.selectall);
    $(document).on('click', '.pay', App.pay);
  },

  select: function (event) {
    event.preventDefault();
    if($(event.target).children("img").length == 1){  //img displaynone,点击的是div
      $(event.target).removeClass('unselect')
      $(event.target).addClass('select')
      $(event.target).children("img").css("display","block")
      //$(event.target).append('<img style="width:24px;height:24px;" src="images/selected.png">')     
    }
    else {     //点击的是img
      $(event.target).css("display","none")
      $(event.target).parent().removeClass('select')
      $(event.target).parent().addClass('unselect')
    }
   
    //parseInt($(event.target).data('id'));
  },

   selectall: function (event) {
    event.preventDefault();
    if($(event.target).children("img").length == 1){  //img displaynone,点击的是div,未选中->选中
      //改变自己的样式
      $(event.target).removeClass('unselect')
      $(event.target).addClass('select')
      $(event.target).children("img").css("display","block")
      //$(event.target).append('<img style="width:24px;height:24px;" src="images/selected.png">')     
      //改变其他按钮，未选中->选中
      $(".choose").each(function(index){
        if($(this).children("img").length == 1){  //img displaynone,点击的是div,未选中->选中
          if(index != $('.choose').length - 1 ){
            $(this).removeClass('unselect')
            $(this).addClass('select')
            $(this).children("img").css("display","block")
          }        
        }
      });
    }
    else {     //点击的是img，选中->未选中
      //改变自己
      $(event.target).css("display","none")
      $(event.target).parent().removeClass('select')
      $(event.target).parent().addClass('unselect')
      //改变其他，选中->未选中
      $(".choose").each(function(index){
        if($(this).hasClass('select') == true){  //点击的是img,选中->未选中         
          $(this).children("img").css("display","none") 
          $(this).removeClass('select')
          $(this).addClass('unselect')      
        }
      });
    }  
  },

  mymoney: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易获取个人账户
      App.adoptionInstance.mymoney({ from: account }).then(function(mymoney) {
        $('.mymoney').text(mymoney)
        
      }).catch(function(err){
        console.log('mymoney',err)
      })
     
    });
  },

  markAdopted: function (adopters, account) {
    var adoptionInstance;

    App.contracts.Adoption.deployed().then(function (instance) {
      adoptionInstance = instance;

      // 调用合约的getAdopters(), 用call读取信息不用消耗gas
      return adoptionInstance.getAdopters.call();
    }).then(function (adopters) {
      for (i = 0; i < adopters.length; i++) {
        if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
          $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
        }
      }
    }).catch(function (err) {
      console.log(err.message);
    });
  },

  getShopcars: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易添加购物车
      App.adoptionInstance.getShopcarsLen(account).then(function(len){
        if(len > 0){
           console.log(len)
          $('.account').text(len)
          $('.account').css("background-color","#ff5947");
          //App.loadShopcar(len-1);
        }
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  addshop: function (event) {
    event.preventDefault();
    var shopId = parseInt($(event.target).data('id'));
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log('addshop',error);
      }
      var account = accounts[0];
      App.adoptionInstance.addshop(shopId, { from: account }).then(function(){
        return App.getShopcars();
      }).catch(function (err) {
        console.log('addshoperr',err.message);
      });
    });
  },

  loadShopcar: function(index) {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.shopcars(account, index).then(function(shopid) {        
        if (index - 1 >= 0) {
         
          App.loadShopcar(index - 1);
        }
      }).catch(function(err) {
          console.log(err)
      });
    })

  },

  jump: function() {
    // window.open("https://tt.wo.cn/auth/attachment/downloadForMobile?id=8064");
    window.location.href="myaccount.html";
  },

  pay: function() {
    $('.choose').each(function(){
      if($(this).hasClass("select") == true){
        let scoreid = $(this).data('scoreid');
        let jifenarr = App.jifenstr.split(",")
        let delindex
        jifenarr.forEach((item,index)=>{
          if(parseInt(item.split("=")[0]) == scoreid){
            delindex = index;
            return;
          }
        })
        jifenarr.splice(delindex,1)
        App.jifenarr = jifenarr
        App.jifenstr = jifenarr.join(",")

        let addmoney = parseInt(parseInt($(this).data('score'))/100);
        web3.eth.getAccounts(function (error, accounts) {
          if (error) {
            console.log(error);
          }
          var account = accounts[0];
          App.adoptionInstance.exchange(addmoney,{ from: account }).then(function() {
            var message = {from: accounts[2], to: account , value: web3.toWei(addmoney/10000, 'ether')};
            web3.eth.sendTransaction(message, (err, res) => {
              if(error){
                console.log('转账',error)
              }  
              else {
                App.adoptionInstance.addTransaction(res,{ from: account }).then(function(){
                  App.adoptionInstance.updatescore(App.jifenid,App.jifenstr,{ from: account }).then(function() {
                  window.location.href="myaccount.html";
                  }).catch(function(err){
                    console.log('update',err)
                  }) 
                }).catch(function(err){
                  console.log('addtranscation',err)
                })

               
              }
  
            })
            
            
          }).catch(function(err){
            console.log('exchange',err)
          }) 
        });  
      }
    });

    // if(App.jifenid == 0){
    //   web3.eth.getAccounts(function (error, accounts) {
    //     if (error) {
    //       console.log(error);
    //     }
    //     var account = accounts[0];
      
    //     App.adoptionInstance.putunicom(App.jifenstr,{from:account}).then(function(){
    //       console.log('chengong')
    //     }).catch(function(err){
    //       console.log('--',err)
    //     }) 
    //   });
    // }
    // else if(App.jifenid == 1){
    //   web3.eth.getAccounts(function (error, accounts) {
    //     if (error) {
    //       console.log(error);
    //     }
    //     var account = accounts[0];
      
    //     App.adoptionInstance.putmobile(App.jifenstr,{from:account}).then(function(){
    //       console.log('chengong')
    //     }).catch(function(err){
    //       console.log('--',err)
    //     }) 
    //   });
    // }
    // else if(App.jifenid == 2){
    //   web3.eth.getAccounts(function (error, accounts) {
    //     if (error) {
    //       console.log(error);
    //     }
    //     var account = accounts[0];
      
    //     App.adoptionInstance.puttele(App.jifenstr,{from:account}).then(function(){
    //       console.log('chengong')
    //     }).catch(function(err){
    //       console.log('--',err)
    //     }) 
    //   });
    // }
    // else if(App.jifenid == 3){
    //   web3.eth.getAccounts(function (error, accounts) {
    //     if (error) {
    //       console.log(error);
    //     }
    //     var account = accounts[0];
      
    //     App.adoptionInstance.putgong(App.jifenstr,{from:account}).then(function(){
    //       console.log('chengong')
    //     }).catch(function(err){
    //       console.log('--',err)
    //     }) 
    //   });
    // }
    //
  },

};

$(function () {
  $(window).on('load',function () {
    App.init();
  });
});

